package com.xqq.utils;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AcledApiRequest {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println("开始下载...");
        String token = "7-*MiPLbG17LwemN17Dx";
        String email = "uyzbm5iuu@tempmail.cn";
        String time = "1745848981899";
        String fileName = "Asia-Pacific_2018-2025_May16";
        String savePath = "F:\\XW\\项目相关\\缅甸\\冲突数据\\"+fileName + ".csv";
        try {
            // 构造目标URL
            String urlString = "https://acleddata.com/acleddatanew/wp-content/plugins/acled-dataset-downloads/authorisation/"
                    + fileName + "/?email=" + email + "&token=" + token + "&time=" + time;

            // 创建HTTP连接
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 设置请求头模拟浏览器访问
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            conn.setRequestProperty("Accept", "text/csv");

            // 检查响应状态
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                try (BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder content = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        content.append(inputLine).append("\n");
                    }
                    // 保存CSV文件
                    saveToCsv(content.toString(), savePath);
                    System.out.println("文件下载成功，保存路径：" + savePath);
                }
            } else {
                System.err.println("下载失败，HTTP状态码：" + responseCode);
            }
            conn.disconnect();
            long duration = System.currentTimeMillis() - start;
            System.out.println("耗时: "+duration/1000+"s" );
            //1. ConflictCsvParser main 函数来过滤数据
            //2. CSVService readCsvAndSaveToDatabase 读取CSV文件，保存到数据库


        } catch (MalformedURLException e) {
            System.err.println("URL格式错误：" + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO异常：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 保存响应内容为 CSV 文件
    private static void saveToCsv(String data, String filePath) {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
